#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

#include "Comm.hpp"
#include "Log.hpp"

static const uint16_t portnull = 8080;
using namespace LogModule;

class Tcpserver
{
public:
    Tcpserver(int port = portnull) : _port(port), _isrunning(false)
    {
    }
    ~Tcpserver() {}
    void InisServer()
    {
        // 1.创建socket
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            // std::cout<<"创建sockfd失败!"<<std::endl;
            // exit(1);
            LOG(LogLevel::FATAL) << "sockfd error";
            Die(SOCKET_ERR);
        }
        // std::cout<<"创建sockfd成功!"<<std::endl;
        LOG(LogLevel::INFO) << "socket info";

        int opt = 1;
        setsockopt(_listensockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        // 2.填充sockaddr_in 信息
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 3.bind
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            // std::cout<<"bind失败!"<<std::endl;
            // exit(BIND_ERR);
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        // std::cout<<"bind成功!"<<std::endl;
        LOG(LogLevel::INFO) << "bind info";

        // 3.监听listen
        n = ::listen(_listensockfd, 8);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen info";

        // 子进程退出，os自动释放资源
        ::signal(SIGCHLD, SIG_IGN);
    }

    void HandlerRequest(int sockfd)
    {
         std::cout <<"进程ID是:" <<  getpid() << std::endl;
        std::cout << "HandlerRequest" << sockfd << std::endl;
        char buffer[1024];
        while (true)
        {
            int n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo_str = "server# ";
                echo_str += buffer;
                ::write(sockfd, echo_str.c_str(), echo_str.size());
            }
            else if (n == 0)
            {
                // 客户端退出
                LOG(LogLevel::WARNING) << "accept 退出,sockfd: " << sockfd;
                break;
            }
            else
            {
                perror("error:");
                break;
            }
        }
        close(sockfd);
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, CONV(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            // 获取连接成功
            LOG(LogLevel::INFO) << "accept info";

            std::cout <<"进程ID是:" <<  getpid() <<  std::endl;
            // v1
            //HandlerRequest(sockfd);
            
            //v2 多线程版本
            pid_t id = fork();
            if(id==0)
            {
                //子进程
                ::close(_listensockfd);
                if(fork()>0) exit(0);//孙子进程
                HandlerRequest(sockfd);
                exit(0);
            }
           // ::close(sockfd);
            int rid = ::waitpid(id,nullptr,0);
            if(rid<0)
            {
                perror("error:");
                LOG(LogLevel::WARNING)<<"waitpid error";
            }

        }
        _isrunning = false;
    }

private:
    int _listensockfd; // 监听socket
    uint16_t _port;
    bool _isrunning;
};